package com.jiujiu.utitls;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ZhaoJunZhou
 * @Date 2020/11/4
 * 创建一些基础的变量用来在freemarker中进行读取
 * 可以直接进行添加回对Freemarker中的基础参数进行修改
 */
public class ContentMap {

    private static volatile Map<String, Object>  expandParameter;
    /**
     * 为0表示没有执行过addParameter
     * 大于0表示执行过addParameter
     * 可以用来对addParameter操作数量进行统计
     */
    private static volatile AtomicInteger state=new AtomicInteger();

    public static Map<String,Object> getExpandParameter(){
        if (expandParameter == null) {
            synchronized (ContentMap.class) {
                ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
                Date date = new Date();
                map.put("nowDATE", DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.format(date));
                map.put("nowTIME", DateFormatUtils.ISO_8601_EXTENDED_TIME_FORMAT.format(date));
                expandParameter = map;
            }
        }

        return expandParameter;
    }

    public synchronized static Map<String, Object> addParameter(Map<String,Object> data) {
        ContentMap.state.addAndGet(1);
        ContentMap.getExpandParameter().putAll(data);
        return ContentMap.getExpandParameter();
    }

    public synchronized static Map<String, Object> addParameter(String key, Object va) {
        ContentMap.getExpandParameter().put(key, va);
        return ContentMap.getExpandParameter();
    }

    public synchronized static Integer getState() {
        return state.get();
    }
}
